

using System;
using System.Collections.Generic;
using System.Text;

using SubSonic;

namespace JTC.MiniCommerce.Store {
  public partial class TransactionController {
  
    #region Constants
    
    private const string TOO_MANY_TRANSACTIONS = "Transaction Collection cannot have more than 1.";
    
    #endregion
  
    #region Methods
    
    #region Public

    /// <summary>
    /// Fetch by order id.
    /// </summary>
    /// <param name="orderId">The order id.</param>
    /// <returns></returns>
    public TransactionCollection FetchByOrderId(int orderId) {
      Query query = new Query(Transaction.Schema).AddWhere(Transaction.Columns.OrderId, orderId);
      TransactionCollection transactionCollection = new TransactionController().FetchByQuery(query);
      transactionCollection.Sort(Transaction.Columns.TransactionDate, true);
      return transactionCollection;
    }

    /// <summary>
    /// Fetch by order id and transaction type id.
    /// </summary>
    /// <param name="orderId">The order id.</param>
    /// <param name="transactionTypeId">The transaction type id.</param>
    /// <returns></returns>
    public Transaction FetchByOrderIdAndTransactionTypeId(int orderId, int transactionTypeId) {
      Transaction transaction = null;
      Query query = new Query(Transaction.Schema).
        AddWhere(Transaction.Columns.OrderId, orderId).
        AddWhere(Transaction.Columns.TransactionTypeId, transactionTypeId);
      TransactionCollection transactionCollection = new TransactionController().FetchByQuery(query);
      if(transactionCollection.Count > 1) {
        throw new InvalidOperationException(TOO_MANY_TRANSACTIONS);
      }
      if(transactionCollection.Count > 0) {
        transaction = transactionCollection[0];
      }
      return transaction;
    }
    
    #endregion
    
    #endregion
    
  }
}
